//
//  MTShopDetailOrderController.m
//  点菜页面
//
//  Created by HaoYoson on 16/7/22.
//  Copyright © 2016年 HaoYoson. All rights reserved.
//

#import "AppDelegate.h"
#import "MTShopDetailOrderController.h"
#import "MTShopDetailOrderFoodCategory.h"
#import "MTShopDetailOrderFoodCategoryCell.h"
#import "MTShopDetailOrderFoodCell.h"
#import "Masonry.h"
#import "UIColor+Addition.h"
#import "UILabel+Addition.h"

static NSString *orderFoodCategoryCellid = @"orderFoodCategoryCellid";
static NSString *orderFoodCellid = @"orderFoodCellid";
@interface MTShopDetailOrderController () <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSArray<MTShopDetailOrderFoodCategory *> *detailOrderData;

@property (strong, nonatomic) UITableView *orderFoodCategoryTableView;
@property (strong, nonatomic) UITableView *orderFoodTableView;

@end

@implementation MTShopDetailOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];

    // 解析数据
    self.detailOrderData = [self loadDetailOrderData];

    // 两个tableView
    UITableView *orderFoodCategoryTableView = [[UITableView alloc] init];    // 左
    UITableView *orderFoodTableView = [[UITableView alloc] init];            // 右
    // 设置数据源和代理
    orderFoodCategoryTableView.delegate = self;
    orderFoodTableView.delegate = self;
    orderFoodCategoryTableView.dataSource = self;
    orderFoodTableView.dataSource = self;
    // 注册单元格
    [orderFoodCategoryTableView registerClass:[MTShopDetailOrderFoodCategoryCell class] forCellReuseIdentifier:orderFoodCategoryCellid];
    [orderFoodTableView registerNib:[UINib nibWithNibName:@"MTShopDetailOrderFoodCell" bundle:nil] forCellReuseIdentifier:orderFoodCellid];
    //    [orderFoodTableView registerClass:[MTShopDetailOrderFoodCell class] forCellReuseIdentifier:orderFoodCellid];
    // 计算行高
    orderFoodCategoryTableView.rowHeight = 60;
    orderFoodTableView.estimatedRowHeight = 128;
    orderFoodTableView.rowHeight = UITableViewAutomaticDimension;
    // 没有数据不现实线
    orderFoodCategoryTableView.tableFooterView = [[UIView alloc] init];
    orderFoodTableView.tableFooterView = [[UIView alloc] init];
    // 添加到视图
    [self.view addSubview:orderFoodCategoryTableView];
    [self.view addSubview:orderFoodTableView];
    // 全局赋值方便代理方法进行判断
    self.orderFoodCategoryTableView = orderFoodCategoryTableView;
    self.orderFoodTableView = orderFoodTableView;

    // 自动布局
    [orderFoodCategoryTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.offset(0);
        make.width.offset(100);
    }];
    [orderFoodTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.offset(0);
        make.left.equalTo(orderFoodCategoryTableView.mas_right);
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // pop回来的时候 不在执行.
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 选中第一项
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

        [self.orderFoodCategoryTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
    });
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == _orderFoodCategoryTableView) {    // 食物分类
        return 0;
    } else {    // 食物
        return 30;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == _orderFoodCategoryTableView) {    // 食物分类
        return nil;
    } else {    // 食物
        UIView *sectionHeader = [[UIView alloc] init];
        sectionHeader.frame = CGRectMake(0, 0, tableView.bounds.size.width, [self tableView:tableView heightForHeaderInSection:section]);
        sectionHeader.backgroundColor = [UIColor colorWithHex:0xf8f8f8];
        UILabel *titleLabel = [UILabel labelWithText:self.detailOrderData[section].name andTextColor:[UIColor darkGrayColor] andFontSize:14];
        titleLabel.frame = sectionHeader.bounds;
        [sectionHeader addSubview:titleLabel];
        return sectionHeader;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _orderFoodCategoryTableView) {    // 食物分类
        return 1;
    } else {    // 食物
        return self.detailOrderData.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _orderFoodCategoryTableView) {    // 食物分类
        return self.detailOrderData.count;
    } else {    // 食物
        return self.detailOrderData[section].spus.count;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _orderFoodCategoryTableView) {    // 食物分类

    } else {    // 食物
        NSArray *visRows = [_orderFoodTableView indexPathsForVisibleRows];
        NSIndexPath *firstPath = [visRows firstObject];
        [_orderFoodCategoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:firstPath.section inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _orderFoodCategoryTableView) {    // 食物分类
        MTShopDetailOrderFoodCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:orderFoodCategoryCellid forIndexPath:indexPath];
        cell.textLabel.text = self.detailOrderData[indexPath.row].name;
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.numberOfLines = 2;
        cell.textLabel.font = [UIFont systemFontOfSize:12];
        return cell;
    } else {    // 食物
        MTShopDetailOrderFoodCell *cell = [tableView dequeueReusableCellWithIdentifier:orderFoodCellid forIndexPath:indexPath];
        cell.food = self.detailOrderData[indexPath.section].spus[indexPath.row];
        //        cell.textLabel.text = self.detailOrderData[indexPath.section].spus[indexPath.row].name;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _orderFoodCategoryTableView) {    // 食物分类
        NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        [_orderFoodTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
    } else {    // 食物

        // 以下代码仅测试在 viewDidAppear 中是否一直都是选中第一组
        UIViewController *vc = [[UIViewController alloc] init];
        vc.view.backgroundColor = [UIColor redColor];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
        [vc.view addSubview:btn];
        [btn addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (void)test {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (NSArray<MTShopDetailOrderFoodCategory *> *)loadDetailOrderData {
    // 文件路径
    NSURL *path = [[NSBundle mainBundle] URLForResource:@"food.json" withExtension:nil];

    // 转data
    NSData *data = [NSData dataWithContentsOfURL:path];

    // 数组
    id res = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSArray *tempArray = res[@"data"][@"food_spu_tags"];

    NSMutableArray *array = [NSMutableArray array];

    // 字典转模型
    for (NSDictionary *dict in tempArray) {
        MTShopDetailOrderFoodCategory *fc = [MTShopDetailOrderFoodCategory shopDetailOrderFoodCategory:dict];
        [array addObject:fc];
    }
    return array.copy;
}

// 处理分割线
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if ([self.orderFoodCategoryTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.orderFoodCategoryTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }

    if ([self.orderFoodCategoryTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.orderFoodCategoryTableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }

    if ([self.orderFoodTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.orderFoodTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }

    if ([self.orderFoodTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.orderFoodTableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
@end
